const {
	getItemByKey
} = Require("utils.libs.src.dao-array");
/**
 * 将item添加到tree数据
 */
function addTreeItem(tree, item, key = '_id', parentCol = 'parent_id') {
	if (!!item[parentCol]) {
		for (let i = 0; i < tree.length; i++) {
			if (item[parentCol] == tree[i][key]) {
				if (!!tree[i].children) {
					tree[i].children.push(item);
				} else {
					tree[i].children = [];
					tree[i].children.push(item);
				}
				return tree
			} else {
				if (!!tree[i].children && tree[i].children.length > 0) {
					addTreeItem(tree[i].children, item, key, parentCol)
				}
			}
		}
	} else {
		tree.push(item)
	}
	return tree
}
/**
 * 根据object更新tree数据
 */
function updateTreeItem(tree, item, key = '_id') {
	for (let i = 0; i < tree.length; i++) {
		if (item[key] == tree[i][key]) {
			tree.splice(i, 1, item)
			return tree
		} else {
			if (!!tree[i].children && tree[i].children.length > 0) {
				updateTreeItem(tree[i].children, item, key)
			}
		}
	}
	return tree
}
/**
 * 根据object删除tree数据
 */
function deleteTreeItem(tree, item, key = '_id') {
	for (let i = 0; i < tree.length; i++) {
		if (item[key] == tree[i][key]) {
			tree.splice(i, 1)
			return tree
		} else {
			if (!!tree[i].children && tree[i].children.length > 0) {
				deleteTreeItem(tree[i].children, item, key)
			}
		}
	}
	return tree
}
/**
 * 得到子节点数据，去除非子节点数据
 */
function getTreeLast(arr, tree, key = '_id') {
	for (let i = 0; i < tree.length; i++) {
		let item = tree[i];
		if (item.children.length > 0) {
			let pos = arr.indexOf(item[key]);
			if (pos >= 0) {
				arr.splice(pos, 1);
			}
			arr = getTreeLast(arr, item.children, key);
		}
	}
	return arr
}
/**
 * 列表数组转换树形数组
 */
function table2tree(vData, vId, vPid) {
	let result = []
	if (!Array.isArray(vData)) {
		// 不是数组直接返回空数组
		return result
	}
	vData.forEach(item => {
		// 删除原有数据children
		delete item.children;
	});
	// 将所有数组放到object
	let map = {};
	vData.forEach(item => {
		map[item[vId]] = item;
	});
	vData.forEach(item => {
		let parent = map[item[vPid]];
		if (parent) {
			// 有父对象将其加入子类中
			(parent.children || (parent.children = [])).push(item);
		} else {
			// 没有父对象直接作为根对象
			result.push(item);
		}
	});
	return result;
}

module.exports = {
	addTreeItem, //增加tree项
	updateTreeItem, //修改tree项
	deleteTreeItem, //删除tree项
	getTreeLast, //得到末级
	table2tree //table数据转换为tree数据
}
